﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
using System.IO;

namespace SAE.Plugin.Demo
{
    public class ImportSiteStructure : SPSAdminJob
    {
        protected override int OnRun(object parameter)
        {            
            if (parameter is SPSite)
            {
                SPSite site = parameter as SPSite;
                for (int i = site.AllWebs.Count - 1; i >= 0; i--)
                {
                    if (!site.AllWebs[i].ID.Equals(site.RootWeb.ID) && site.AllWebs[i].Title!="Search")
                    {
                        site.AllWebs[i].Delete();
                    }
                }

                XmlDocument xDoc=new XmlDocument();
                xDoc.Load("sitestructure.xml");

                base.TotalProgressMaximumStep = (parameter as SPSite).AllWebs.Count;

                if (xDoc.ChildNodes.Count == 1)
                {
                    ReportCurrentProgress(1, xDoc.ChildNodes[0].Name);

                    SPWeb rootWeb = (parameter as SPSite).RootWeb;
                    ReviewWebNode(xDoc.ChildNodes[0],rootWeb);
                }         
            }

            return 1;
        }

        void ReviewWebNode(XmlNode node,SPWeb web)
        {
            foreach (XmlNode childNode in node.ChildNodes)
            {
                string childWebTitle=XmlConvert.DecodeName(childNode.Name);  
              
                string childWebUrl=childNode.NamespaceURI.ToLower();

                if(childWebUrl.StartsWith(web.ServerRelativeUrl.ToLower()))
                {
                    childWebUrl=childWebUrl.Remove(0,web.ServerRelativeUrl.Length).TrimStart('/');
                }

                SPWeb childWeb;

                if (web.Webs[childWebUrl].Exists)
                {
                    childWeb = web.Webs[childWebUrl];
                }
                else
                {
                    childWeb = web.Webs.Add(childWebUrl, childWebTitle, childWebTitle
                    , 1033, "FASTNET", false, false);
                    childWeb.Navigation.UseShared = true;
                    childWeb.Update();
                }
                
                ReportCurrentProgress(1, childWebTitle + " - " + childNode.NamespaceURI);

                ReviewWebNode(childNode,childWeb);
            }
        }
    }
}
